package com.shenganyuan.smac.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

import com.oklib.utils.crypt.Md5;
import com.oklib.utils.helper.RxUtil;
import com.oklib.utils.network.http.ViseHttp;
import com.oklib.utils.network.http.callback.ACallback;
import com.oklib.utils.network.http.subscriber.ApiCallbackSubscriber;
import com.oklib.utils.pref.AnyPref;
import com.oklib.utils.view.SnackbarUtil;
import com.oklib.utils.view.ToastUtils;
import com.shenganyuan.smac.App;
import com.shenganyuan.smac.R;
import com.shenganyuan.smac.common.BaseActivity;
import com.shenganyuan.smac.common.Config;
import com.shenganyuan.smac.common.beans.APILoginParam;
import com.shenganyuan.smac.common.beans.ApiLoginUser;
import com.shenganyuan.smac.common.data.Api;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * @author Damon
 */
public class ActLogin extends BaseActivity {


    @BindView(R.id.toolbar)
    Toolbar actionBar;
    @BindView(R.id.login_username)
    EditText loginUsername;
    @BindView(R.id.login_password)
    EditText loginPassword;
    @BindView(R.id.cb_show_pwd)
    CheckBox cbShowPwd;
    @BindView(R.id.login_button)
    Button loginButton;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initUI(Bundle savedInstanceState) {
        cbShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int inputType = loginPassword.getInputType();
                if (inputType != InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
                    loginPassword
                            .setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    loginPassword.setInputType(InputType.TYPE_CLASS_TEXT
                            | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                String pwd = loginPassword.getText().toString().trim();
                if (!TextUtils.isEmpty(pwd)) {
                    loginPassword.setSelection(pwd.length());
                }
            }
        });
        initLoginBtState();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    private void initLoginBtState() {
        changeLoginState();
        EditTextListner textListner = new EditTextListner();
        loginUsername.addTextChangedListener(textListner);
        loginPassword.addTextChangedListener(textListner);
    }

    private void changeLoginState() {
        String userName = loginUsername.getText().toString().trim();
        String password = loginPassword.getText().toString().trim();
        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
            loginButton.setEnabled(false);
        } else {
            loginButton.setEnabled(true);
        }
    }

    private class EditTextListner implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            changeLoginState();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    private boolean toLogin() {
        return true;
    }

    @OnClick(R.id.cb_show_pwd)
    public void onCbShowPwdClicked() {
    }

    @OnClick(R.id.login_button)
    public void onLoginButtonClicked() {
        if (TextUtils.isEmpty(loginUsername.getText())) {
            SnackbarUtil.showShort(getWindow().getDecorView(), "用户名不能为空");
            return;
        }
        if (TextUtils.isEmpty(loginPassword.getText())) {
            SnackbarUtil.showShort(getWindow().getDecorView(), "密码不能为空");
            return;
        }
        String username = loginUsername.getText().toString().trim();
        String pass = Md5.getMd5ByString(loginPassword.getText().toString().trim());
        loginCall(username, pass);
    }

    /**
     * 登录请求
     *
     * @param username
     * @param pass
     */
    private void loginCall(String username, String pass) {
        ViseHttp.RETROFIT().create(Api.class).login(username, pass)
                .compose(RxUtil.rxSchedulerHelper())
                .subscribe(new ApiCallbackSubscriber<>(new ACallback<ApiLoginUser>() {
                    @Override
                    public void onSuccess(ApiLoginUser apiUser) {
                        try {
                            if (apiUser != null) {
                                if ("true".equalsIgnoreCase(apiUser.getResult())) {
                                    Intent intent = new Intent();
                                    intent.putExtra("data", apiUser.getDjuser());
                                    App.setCurrentUserAndToken(apiUser.getDjuser(), apiUser.getAccess_token());
                                    APILoginParam apiLoginParam = new APILoginParam();
                                    apiLoginParam.name = username;
                                    apiLoginParam.password = pass;
                                    App.saveUserLoginPara(apiLoginParam);
                                    intent.setClass(ActLogin.this, MainActivity.class);
                                    startActivity(intent);
                                    ToastUtils.showToast(mContext, apiUser.getMessage());
                                    AnyPref.getDefault().putBoolean(Config.PrefKey.KEY_APP_FIRST_START, false);
                                    finish();
                                } else {
                                    ToastUtils.showToast(mContext, apiUser.getMessage());
                                }
                            } else {
                                ToastUtils.showToast(mContext, "登录失败");
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        ToastUtils.showToast(mContext, "登录失败");
                    }
                }));
    }

}

